from django.shortcuts import render

# Create your views here.
from django_filters.rest_framework import DjangoFilterBackend
from rest_framework.filters import OrderingFilter
from rest_framework.generics import GenericAPIView, ListAPIView
from rest_framework.response import Response

from goods.models import GoodsCategory, SKU
from goods.serializers import ChannelSerializer, CategorySerializer, SKUSerializer


class CategoryView(GenericAPIView):
    """商品列表页面包屑导航"""
    queryset = GoodsCategory.objects.all()

    # GET /categories/1/
    def get(self, request, pk=None):
        ret = {
            'cat1': '',
            'cat2': '',
            'cat3': '',
        }
        category = self.get_object()
        if category.parent is None:
            # 当前类别为一级类别
            # 通过 频道 查询 类别：  category.goodschannel_set.all()[0]
            ret['cat1'] = ChannelSerializer(category.goodschannel_set.all()[0]).data
        elif category.goodscategory_set.count() == 0:
            # 当前类别为三级
            ret['cat3'] = CategorySerializer(category).data
            cat2 = category.parent
            ret['cat2'] = CategorySerializer(cat2).data
            ret['cat1'] = ChannelSerializer(cat2.parent.goodschannel_set.all()[0]).data
        else:
            # 当前类别为二级
            ret['cat2'] = CategorySerializer(category).data
            ret['cat1'] = ChannelSerializer(category.parent.goodschannel_set.all()[0]).data

        return Response(ret)


class SKUListView(ListAPIView):
    """查询商品列表数据"""
    serializer_class = SKUSerializer
    queryset = SKU.objects.filter(is_launched=True)  # 只查询上架商品

    # 配置排序和过滤的管理类
    filter_backends = (OrderingFilter, DjangoFilterBackend)
    ordering_fields = ('id',  'price', 'sales')  # 排序字段
    filter_fields = ('category_id', )  # 过滤字段

